package controllers

import (
	"github.com/goravel/framework/contracts/http"
	httpfacade "github.com/hulutech-web/http_result"
	"goravel/app/services/captcha"
)

type CaptchaController struct {
	// Dependent services
	captcha *captcha.CaptchaService
}

func NewCaptchaController() *CaptchaController {
	return &CaptchaController{
		captcha: captcha.NewCaptchaService(),
	}
}

// GetCaptcha manager 图形验证码
// @Summary 图形验证码
// @Description 图形滑动验证。
// @Tags CaptchaController
// @Accept json
// @Produce json
// @Id GetCaptcha
// @Success 200 {string} json {}
// @OperationID Captcha
// @Router   /api/captcha [get]
func (r *CaptchaController) GetCaptcha(ctx http.Context) http.Response {
	data := r.captcha.GetSlideBasicCaptData()
	return httpfacade.NewResult(ctx).Success("", data)
}

type Req struct {
	Point captcha.Point `json:"point" form:"point"`
	Key   string        `json:"key" form:"key"`
}

type SuccessResponse struct {
	Code string `json:"code"`
}

// ValidateCaptcha manager 图形验证码
// @Summary 图形验证码
// @Description 图形滑动验证。
// @Tags CaptchaController
// @Accept json
// @Produce json
// @Param captchaData body Req true "验证点位置数据"
// @Id CaptchaValidateCaptcha
// @Success 200 {string} json {}
// @OperationID ValidateCaptcha
// @Router   /api/validate [post]
func (r *CaptchaController) ValidateCaptcha(ctx http.Context) http.Response {
	req := &Req{}
	if err := ctx.Request().Bind(req); err != nil {
		return httpfacade.NewResult(ctx).Error(422, "参数错误", err.Error())
	}
	code, isOk, err := r.captcha.CheckSlideData(req.Key, req.Point)
	if err != nil || isOk != true {
		return httpfacade.NewResult(ctx).Error(422, "参数错误", err.Error())
	}
	return httpfacade.NewResult(ctx).Success("", map[string]interface{}{
		"code": code,
	})
}
